import React, {
    Component
} from 'react';
import GridTable from '../../components/display/gridTable';
import {
    Button,
    DatePicker,
    Tooltip,
    Row,
    Col,
    Divider,
    message,
    Spin,
    Input,
    Modal
} from 'antd';
import ScModal from '../../components/feedback/scModal';
import {
    findOrderList,
    getOrderDetail,
    processData,
    chargeStop,
    getUserInfo,
    refund
} from '../../fetch/fetchApi';
import locale from "antd/lib/date-picker/locale/zh_CN";
import Epile from "./ePile";
import PropsType from "prop-types";
const {
    RangePicker
} = DatePicker;

class Orderlist extends Component {
    constructor(props) {
        super(props);
        this.props = props;
        this.state = {
            gridData: null,
            loadingmes: '查询',
            loading: !1,
            btnloading: !1,
            detailData: null,
            rangeValue: null,
            spinLoading: !1,
            pagination: {
                total: 0
            }
        };
        this.init();
        window.LayoutTab && setTimeout(() => {
            this.queryChargeInfo();
        }, 1);
    }

    init() {
        this.query = {
            page: '1',
            pagecount: '10'
        };
        this.query['stubId'] = window.LayoutTab.tabParam.stubId;
        this.query['userId'] = window.LayoutTab.tabParam.userId;
        this.query['appkeyType'] = window.LayoutTab.tabParam.appkeyType;
        this.params = {};
        // 设置表头
        this.tableColumns = [{
            title: '平台订单号',
            dataIndex: 'key',
            key: 'key',
            fixed: 'left',
            width: 100,
        }, {
            title: '桩群名称',
            dataIndex: 'stubGroupName',
            key: 'stubGroupName'
        }, {
            title: '充电时间',
            dataIndex: 'timeStart',
            key: 'timeStart',
            className: 'column-nowrap',
            render: (text, record) => (
                <Tooltip placement="topLeft" title={text} >
            {text}
          </Tooltip>)
        }, {
            title: '电桩编号',
            dataIndex: 'stubId',
            key: 'stubId',
        }, {
            title: '电量 (度)',
            dataIndex: 'power',
            key: 'power',
        }, {
            title: '时长 (分)',
            dataIndex: 'chargeTime',
            key: 'chargeTime',
        }, {
            title: '电费 (元)',
            dataIndex: 'feeElectric',
            key: 'feeElectric',
        }, {
            title: '服务费 (元)',
            dataIndex: 'feeService',
            key: 'feeService',
            className: 'column-nowrap',
            render: (text, record) => (
                <Tooltip placement="topLeft" title={text} >
            {text}
          </Tooltip>)
        }, {
            title: '订单金额 (元)',
            dataIndex: 'feeTotal',
            key: 'feeTotal'
        }, {
            title: '充电状态',
            dataIndex: 'status',
            key: 'status',
            render: (text, record) => (
                <div>{text === 1 ? '充电中' : '订单结束'}</div>
            )
        }, {
            title: '停止原因',
            dataIndex: 'endInfo',
            key: 'endInfo',
            className: 'column-nowrap'
        }, {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 100,
            render: (text, record) => (
                <div className="action-wrap">
            <a href="javascript:void(0);" onClick={() => this.showOrderDetail(record.key, '订单详情')}>订单详情</a>
            <Divider type="vertical" />
            <a href="javascript:void(0);" onClick={() => this.openTab({
                        'keyId': `progresschart${record.key}`,
                        'orderId': record.key
                    }, {
                        'key': 'progresschart',
                        titleText: '充电过程'
                    })}>充电过程</a>
            <Divider type="vertical" />
            {record.status !== 1 || <a href="javascript:void(0);" onClick={() => this.stopOrder(record.key)}>停止订单</a>}
          </div>
            )
        }];
    }

    // 停止订单
    stopOrder(orderNo) {
        this.setState({
            loading: true
        })
        const res = chargeStop({
            orderId: orderNo
        });
        res.then((data) => {
            if (data.data.code === "200") {
                alert("操作成功");
                this.findOrderListCb();
            } else {
                alert(data.data.text || "操作失败");
            }
        }, (error) => {
            console.log(error);
        }).catch((ex) => {
            console.log(ex);
        })

    }

    // 打开tab
    openTab(param, e) {
        this.props.onAdd.bind(window.LayoutTab)(e, param);
    }

    // fetch DataSource
    async findOrderList() {
        this.setState({
            loading: !0,
            btnloading: !0
        });
        try {
            const resData = await findOrderList(this.query);
            let resObj = resData.data.data;
            if (resData.data.code === '200') {
                for (let r of resObj) {
                    r.timeStart = r.timeStart + ' - ' + (r.timeEnd ? r.timeEnd : '---');
                }
                const pagination = {
                    total: resData.data.pageLimit.totalCount,
                    onShowSizeChange: (current) => {
                        this.turnPage(current)
                    },
                    onChange: (current) => {
                        this.turnPage(current)
                    }
                }
                this.setState({
                    pagination
                });
                return resObj;
            }
        } catch (e) {
            console.log(e);
        }
    }

    // 提交查询
    queryChargeInfo() {
        this.query.page = '1';
        this.state.pagination.current = 1;
        this.setState({
            pagination: this.state.pagination
        });
        this.findOrderListCb();
    }

    findOrderListCb() {
        this.findOrderList().then((data) => {
            this.setState({
                loading: !1,
                btnloading: !1,
                gridData: data
            });
        });
    }

    // 注入电桩编号参数
    pileInputHandler(e) {
        this.query['stubId'] = e.target.value.toString();
    }

    // 注入电站名称
    powerStationInputHandler(e) {
        this.query['keywords'] = e.target.value.toString();
    }

    // 选择年份
    onDataChange(e) {
        if (e[1] - e[0] > 7 * 24 * 60 * 6e4) {
            message.warn('选择范围请在7天内', 1);
            this.setState({
                'rangeValue': null
            });
            this.query['startTime'] = '';
            this.query['endTime'] = '';
            return;
        };
        this.setState({
            'rangeValue': e
        });
        this.query['startTime'] = e[0] && e[0].format('YYYY.MM.DD HH:mm:ss').toString();
        this.query['endTime'] = e[1] && e[1].format('YYYY.MM.DD HH:mm:ss').toString();
    }

    filterDataHandler(t) {
        return t !== null ? t : '--';
    }

    // 显示订单详情
    showOrderDetail(id, title) {
        this.setState({
            width: 800,
            modalVisible: !0,
            modalTitle: title,
            modalName: 'orderdetail',
            spinLoading: !0
        });
        this.getOrderDetail(id).then(() => {
            this.setState({
                spinLoading: !1
            });
        });
    }

    // fetch 订单详情
    async getOrderDetail(id) {
        try {
            const resData = await getOrderDetail({
                orderId: id,
            });
            if (resData.data.code === '200') {
                this.setState({
                    detailData: resData.data.data,
                    spinLoading: !1
                });
            }
        } catch (e) {
            console.log(e);
        }
    }

    // 跳转页码
    turnPage(current) {
        this.query['page'] = current.toString();
        this.findOrderListCb();
    }

    // 取消弹窗
    cancel() {
        this.setState({
            modalVisible: !1,
            confirmLoading: !1
        });
    }

    // 订单号查询
    orderNoInputChangeHandle = (e) => {
        this.query['outOrderId'] = e.target.value;
    }

    // 获取用户详情
    getUserDetail = (account) => {
        this.setState({
            userModalVisible: true,
            userSpinLoading: true
        });
        const res = getUserInfo({
            account: account
        });
        res.then((data) => {
            this.setState({
                userSpinLoading: false,
                user: data.data.data
            });
        })
    }

    // 处理用户模态框点击事件
    handleUserModalOk = () => {
        this.setState({
            userModalVisible: false
        });
    }

    handleRefund = (orderId) => {
        refund({
            rechargeId: orderId,
            appkeyType: this.query.appkeyType
        }).then((res) => {
            console.log(res);
            if (res && res.data.code === "200") {
                message.success("退款成功");
            }
        })
    }

    render() {
        const Content = <div className="sc-page-content">
      <div className="page-toolbar">
        <Row gutter={8}>
          <Col span={6} >
            <RangePicker value={this.state.rangeValue} onChange={this.onDataChange.bind(this)} locale={locale} format="YYYY-MM-DD HH:mm:ss" className={'picker-100'}/>
          </Col>
          <Col span={4} className="whole-fill">
            <Input placeholder="业务订单号" onChange={this.orderNoInputChangeHandle}/>
          </Col>
          <div  className="button-inlineBlock">
            <Button type="primary" onClick={this.queryChargeInfo.bind(this)} loading={this.state.loading}>{this.state.loadingmes}</Button>
          </div>
        </Row>
      </div>
      <div className="page-panel">
        <GridTable postyle="table-center" data={this.state.gridData} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
        <ScModal width={this.state.width} modalVisible={this.state.modalVisible} modalTitle={this.state.modalTitle} modalContent={<div className="sc-modal-scroll">
            {this.state.spinLoading && <Spin className={'loadingMiddle'}/>}
            {this.state.detailData && <div className="modal-list">
              <div className={"modal-flex"}>
                <div className={"modal-flex-1"}>
                  <ul>
                    <li>
                      <strong>平台订单号:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.id)}</span>
                    </li>
                    <li>
                      <strong>业务订单号:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.outOrderId)}</span>
                    </li>
                    <li>
                      <strong>充电应用:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.appStr)}</span>
                    </li>
                    <li>
                      <strong>充电用户:</strong>
                      <span style={{
            width: 100
        }}>{this.filterDataHandler(this.state.detailData.account)}</span>
                      <a href="javascript:void(0);" onClick={() => this.getUserDetail(this.state.detailData.account)}>查看详情</a>
                    </li>
                    <li>
                      <strong>充电时间:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.timeStart)} - {this.filterDataHandler(this.state.detailData.timeEnd)}</span>
                    </li>
                    <li>
                      <strong>电桩编号:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.stubId)}</span>
                    </li>
                    <li>
                      <strong>电站名称:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.stubGroupName)}</span>
                    </li>
                    <li>
                      <strong>运营类型:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.stubGroupType === null ? '--' : (this.state.detailData.stubGroupType === 0 ? '非自营' : '自营'))}</span>
                    </li>
                    <li>
                      <strong>电站城市:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.cityStr)}</span>
                    </li>
                    <li>
                      <strong>支付方式:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.payTypeInfo)}</span>
                    </li>
                  </ul>
                </div>
                <div className={"modal-flex-1"}>
                  <ul>
                    <li>
                      <strong>充电电量:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.power)}</span>
                    </li>
                    <li>
                      <strong>充电时长:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.chargeTime)}</span>
                    </li>
                    <li>
                      <strong>充电状态:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.status === 9 ? '充电完成' : '充电中')}</span>
                    </li>
                    <li>
                      <strong>订单金额:</strong>
                      <span>{this.filterDataHandler(parseFloat(this.state.detailData.feeTotal) + parseFloat(!this.state.detailData.feeDiscount ? 0 : (this.state.detailData.feeDiscount[0] + this.state.detailData.feeDiscount[1])))}</span>
                    </li>
                    <li>
                      <strong>折扣类型:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.discountTypeStr)}</span>
                    </li>
                    <li>
                      <strong>折扣金额:</strong>
                      <span>{this.filterDataHandler(!this.state.detailData.feeDiscount ? '--' : (this.state.detailData.feeDiscount[0] + this.state.detailData.feeDiscount[1]))}</span>
                    </li>
                    <li>
                      <strong>应付金额:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.feeTotal)}</span>
                    </li>
                    <li>
                      <strong>抵扣金额:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.voucherMoney)}</span>
                    </li>
                    <li>
                      <strong>实付金额:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.accountMoney)}</span>
                    </li>
                    <li>
                      <strong>停止原因:</strong>
                      <span>{this.filterDataHandler(this.state.detailData.endInfo)}</span>
                    </li>
                    <li>
                        <strong>退款状态:</strong>
                        <span style={{'width':'100px'}}>{this.filterDataHandler(this.state.detailData.payType===2?(this.state.detailData.refundStatus==="0"?"退款失败":(this.state.detailData.refundStatus?"退款成功":"无需退款")):"--")}</span>
                        {this.state.detailData.payType===2&&this.state.detailData.refundStatus==="0"&&<a href="javascript:void(0);" onClick={()=>this.handleRefund(this.state.detailData.rechargeId)}>退款</a>}
                    </li>
                  </ul>
                </div>
              </div>
            </div>}
          </div>}
        footer={null}
        cancel={this.cancel.bind(this)}
        />
      </div> <
            Modal title = "用户详情"
        visible = {
            this.state.userModalVisible
        }
        onOk = {
            this.handleUserModalOk
        }
        onCancel = {
                this.handleUserModalOk
            } >
            <Spin spinning={this.state.userSpinLoading}>
          {this.state.user && <div className="modal-list">
            <div className={"modal-flex"}>
              <div className={"modal-flex-1"}>
                <ul>
                  <li>
                    <strong>账户:</strong>
                    <span>{this.state.user.account}</span>
                  </li>
                  <li>
                    <strong>注册时间:</strong>
                    <span>{this.state.user.createTime}</span>
                  </li>
                  <li>
                    <strong>归属地:</strong>
                    <span>{this.state.user.cityStr}</span>
                  </li>
                  <li>
                    <strong>用户等级:</strong>
                    <span>{this.state.user.level}</span>
                  </li>
                  <li>
                    <strong>积分余额:</strong>
                    <span>{this.state.user.validIntegral}</span>
                  </li>
                  <li>
                    <strong>碳 余 额:</strong>
                    <span>{this.state.user.validEmissionReduction}</span>
                  </li>
                  <li>
                    <strong>累计碳资产:</strong>
                    <span>{this.state.user.carbonEmissionReduction}</span>
                  </li>
                  <li>
                    <strong>个人账户:</strong>
                    <span>{this.state.user.amount}</span>
                  </li>
                </ul>
              </div>
            </div>
          </div>}
        </Spin> <
            /Modal> < /
        div > ;

        return Content;
    }
}

export default Orderlist;

Orderlist.propTypes = {
    onAdd: PropsType.func
}